<?php

namespace app\erp\model;

use think\Model;
use app\erp\validate\Memberrule;

class Memberdb extends Model
{
    protected $pk = 'member_id';
    protected $name = 'member';
    protected $autoWriteTimestamp = true;
    protected $readonly = [
        'username'
    ];
    protected $type = [
        'start_time' => 'timestamp:Y-m-d',
        'delete_time' => 'timestamp:Y-m-d'
    ];
    protected $auto = [
        'last_ip'
    ];
    protected $insert = [
        'state' => 1,
        'site_id'
    ];

    protected function setSiteIdAttr($value)
    {
        if (!$value) {
            return SITE_ID;
        }
        if ($value == 0) {
            return null;
        }
        return $value;
    }

    // 自动完成
    protected function setLastIpAttr()
    {
        return request()->ip();
    }

    public $param = array();

    // 查询用户名
    public function scopeUsername($query, $username)
    {
        $query->where('username', $username);
    }

    public function scopeUsernameLike($query, $username_like)
    {
        $query->where('username|realname', 'like', '%' . $username_like . '%');
    }

    // 查询密码
    public function scopePassword($query, $password)
    {
        $query->where('password', password($password));
    }

    public function scopeMemberId($query, $member_id)
    {
        $query->where('member_id', $member_id);
    }

    public function scopeIsManage($query, $is_manage)
    {
        $query->where('is_manage', $is_manage);
    }

    public function scopeSiteId($query, $site_id)
    {
        $this->where('site_id', $site_id);
    }

    public function scopeIsSupplier($query, $is_supplier)
    {
        $query->where('is_supplier', $is_supplier);
    }

    public function base($query)
    {
        if (isset ($this->param ['username']) && $this->param ['username']) {
            $query->username($this->param ['username']);
        }
        if (isset ($this->param ['password']) && $this->param ['password']) {
            $query->password($this->param ['password']);
        }
        if (isset ($this->param ['member_id']) && $this->param ['member_id']) {
            $query->memberId($this->param ['member_id']);
        }
        if (isset ($this->param ['is_manage']) && $this->param ['is_manage']) {
            $query->isManage($this->param ['is_manage']);
        }
        if (isset ($this->param ['username_like']) && $this->param ['username_like']) {
            $query->usernameLike($this->param ['username_like']);
        }
        if (isset ($this->param ['site_id']) && $this->param ['site_id'] > 0) {
            $query->siteId($this->param ['site_id']);
        }
        if (isset ($this->param ['is_supplier']) && $this->param ['is_supplier']) {
            $this->isSupplier($this->param['is_supplier']);
        }
    }

    public function ajaxFind()
    {
        $data = $this->master()->find();
        if ($data) {
            $data = $data->toArray();
            $data = $this->handleData($data);
            return $data;
        } else {
            return 'fail';
        }
    }

    // 查询列表
    public function ajaxSelect()
    {
        $data = $this->ajaxList();
        $count = $this->ajaxCount();
        $return ['data'] = $data;
        $return ['count'] = $count;
        return $return;
    }

    public function ajaxCount()
    {
        return $this->count();
    }

    public function ajaxList()
    {
        $data = $this->order($this->param ['_o'], $this->param ['_b'])->page($this->param ['page'], $this->param ['limit'])->select();
        if (!$data->isEmpty()) {
            $data = $data->toArray();
            foreach ($data as $key => $val) {
                $data [$key] = $this->handleData($val);
            }
        }
        return $data;
    }

    // 登录
    public function login($member_id)
    {
        $this->loginLog('总系统登录');
        $member = $this->get($member_id);
        $member->last_login_time = $member->update_time;
        $member->is_online = 1;
        if (isset ($this->param ['no_session']) && $this->param ['no_sesstion'] = 'yes') {
        } else {
            session('member_id', $member_id);
        }
        $member->save();
    }

    // 供应商登录
    public function supplierLogin($member_id)
    {
        $this->loginLog('总系统供应商登录');
        $member = $this->get($member_id);
        $member->last_login_time = $member->update_time;
        $member->is_online = 1;
        if (isset ($this->param ['no_session']) && $this->param ['no_sesstion'] = 'yes') {
        } else {
            session('supplier_id', $member_id);
        }
        $member->save();
    }

    // 登录日志
    protected function loginLog($login_sys)
    {
        $request = request();
        $save_data = [];
        $save_data['login_sys'] = $login_sys;
        $save_data['username'] = $request->post('username');
        $save_data['login_ip'] = $request->ip();
        $save_data['login_time'] = time();
        $save_data['agent'] = $request->server('HTTP_USER_AGENT');
        $save_data['mac'] = $this->getMac();
        $memberLogdb = new \app\erp\model\MemberLogdb();
        $memberLogdb->save($save_data);
    }

    // 获取mac地址
    protected function getMac()
    {
        return PHP_OS;
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            return 'win';
            $mac = shell_exec('ipconfig /all | findstr "Physical Address"');
            $mac = trim($mac);
            $mac = str_replace('Physical Address: ', '', $mac);
            $mac = str_replace('-', ':', $mac);
        } else {
            return 'mac';
            $mac = shell_exec('ifconfig | grep ether | awk \'{print $2}\'');
        }
        return $mac;
    }

    // 查询是否登录状态
    public function chkOnline($member_id)
    {
        $member = $this->get($member_id);
        if ($member->is_online == 1) {
            return 'success';
        } else {
            return 'fail';
        }
    }

    public function modifyPassword()
    {
        if (!isset ($this->param ['new_password']) || strlen(trim($this->param ['new_password'])) < 6) {
            return '密码长度最少6位，且不能为空';
        }
        $member = $this->find();
        if ($member) {
            $this->save([
                'password' => password($this->param ['new_password'])
            ], [
                'member_id' => $member ['member_id']
            ]);
            return 'success';
        } else {
            return '原始密码错误';
        }
    }

    // 退出
    public function logout($member_id)
    {
        $member = $this->get($member_id);
        $member->is_online = 2;
        if (isset ($this->param ['no_session']) && $this->param ['no_sesstion'] = 'yes') {
        } else {
            session_destroy();
        }
        $member->save();
    }

    // 查询会员信息
    public function memberInfo($member_id)
    {
        $member = $this->get($member_id);
        if ($member) {
            $data = $member->toArray();
            $data = $this->handleData($data);
            return $data;
        } else {
            return array();
        }
    }

    /**
     *
     * @todo 保存数据
     */
    public function ajaxSave()
    {
        $rule = new Memberrule ();

        if (isset ($this->param ['member_id']) && $this->param ['member_id'] != '') {
            if (!$rule->scene('edit')->check($this->param)) {
                return $rule->getError();
            }
            if (isset ($this->param ['password']) && $this->param ['password'] != '') {
                if (strlen(trim($this->param ['password'])) < 6) {
                    return '密码长度最少6位';
                }
                $this->param ['password'] = password($this->param ['password']);
            } else {
                unset ($this->param ['password']);
            }
            $member_id = $this->param ['member_id'];
            unset ($this->param ['member_id']);
            $this->save($this->param, [
                'member_id' => $member_id
            ]);
        } else {
            if (!$rule->check($this->param)) {
                return $rule->getError();
            }
            if (!isset ($this->param ['password']) || strlen(trim($this->param ['password'])) < 6) {
                return '密码长度最少6位，且不能为空';
            }
            $this->param ['password'] = password($this->param ['password']);
            $this->allowField(true)->save($this->param);
        }
        return 'success';
    }

    protected function handleData($val)
    {
        foreach ($val as $k => $v) {
            $val [$k] = $v;
            switch ($k) {
                case 'zhang_picture':
                    if ($v) {
                        $uploaddb = new Uploaddb();
                        $val['zhang_picture'] = $uploaddb->getFind($v);
                    }
                    break;
                case 'head_pic_url' :
                    if ($val ['head_pic_url']) {
                        $val ['head_pic_url'] = $_SERVER ['REQUEST_SCHEME'] . '://' . $_SERVER ['HTTP_HOST'] . $val ['head_pic_url'];
                    }
                    break;
                default :
                    break;
            }
        }
        return $val;
    }
}